import { asyncRoutes, constantRoutes } from '@/router'
import Layout from '@/views/layout/Layout'
/**
 * 通过meta.perms判断是否与当前用户权限匹配
 * @param perms
 * @param route
 */
function hasPermission(perms, route) { // 判断路由是否包含roles
  if (route.meta && route.meta.perms) {
    return perms.some(perm => route.meta.perms.includes(perm))
  } else {
    return true
  }
}

/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param routes asyncRoutes
 * @param perms
 */
function filterAsyncRoutes(routes, perms) {
  const res = []

  routes.forEach(route => { // 循环动态添加的路由钩子
    let item = { ...route }
    let tmp={
      // path: item.level===1?item.data.routerKey:item.data.routerKey.substring(item.data.routerKey.lastIndexOf("/")),
      path: item.data.routerKey,
      component: item.level===1?Layout:() => Promise.resolve(require(`@/views${item.data.routerKey}`).default),
      // redirect: 'noredirect',
      alwaysShow: item.children&&item.children.length>0,
      // alwaysShow: item.level===1&&item.children,
      // name: item.data.label,
      meta: {
        title: item.data.label,
        icon: item.data.ico
      },
    }
    if (item.children) {
      // tmp.children=item.children
      tmp.children = filterAsyncRoutes(item.children, perms)
      // if (tmp.children && tmp.children.length > 0) { // 有子路由判断子路由
      //   res.push(tmp)
      // }
      res.push(tmp)
    } else {
      // if (hasPermission(perms, tmp)) { // 判断路由是否满足roles
      //   res.push(tmp)
      // }
      res.push(tmp)
    }
  })
  // console.log("组装后的动态路由",res)
  return res
}
// function filterAsyncRoutes(routes, perms) {
//   const res = []

//   routes.forEach(route => { // 循环动态添加的路由钩子
//     let item = { ...route }
//     let tmp={
//       path: item.data.routerKey,
//       component: Layout,
//       redirect: 'noredirect',
//       alwaysShow: true,
//       // name: item.data.label,
//       meta: {
//         title: item.data.label,
//         icon: item.data.ico
//       },
//       children:[]
//     }
//     if (item.children) {
//       item.children.forEach(v=>{
//         let item1 = { ...v }
//         let tmp1={
//           path: item1.data.routerKey,
//           component: () => Promise.resolve(require(`@/views${item1.data.routerKey}`).default),
//           redirect: 'noredirect',
//           alwaysShow: true,
//           meta: {
//             title: item1.data.label,
//             icon: item1.data.ico
//           },
//         }
//         tmp.children.push(tmp1)
//       })
      
//     } else {
//       res.push(tmp)
//     }
//   })

//   return res
// }

const permission = {
  state: {
    routes: constantRoutes,
    addRoutes: []
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes
      state.routes = constantRoutes.concat(routes)
    }
  },
  actions: {
    GenerateRoutes({ commit }, data) {
      return new Promise(resolve => {
        const { perms,routers } = data
        let accessedRoutes
        // if (perms.includes('*')) { // 超级管理员左右路由都可看
        //   accessedRoutes = asyncRoutes
        // } else {
        //   accessedRoutes = filterAsyncRoutes(asyncRoutes, perms)// 其它权限进行判断
        // }
        accessedRoutes = filterAsyncRoutes(routers, perms)// 其它权限进行判断

        // let newRoutes=JSON.parse(JSON.stringify(accessedRoutes))
        // let firstRoute=accessedRoutes[0]
        // console.log("firstRoute",firstRoute)
        // if(firstRoute&&firstRoute.path=='/dashboard'){
        //   constantRoutes[constantRoutes.length-1].children[0].meta.icon=accessedRoutes[0].meta.icon
        //   accessedRoutes.shift()
        //   console.log("accessedRoutes",accessedRoutes)
        // }else{
        //   let redirect="dashboard"
        //   if(firstRoute.children){
        //     redirect=firstRoute.children[0].path
        //   }else{
        //     redirect=firstRoute.path
        //   }
        //   constantRoutes.unshift(
        //     {
        //       path: '',
        //       component: Layout,
        //       redirect,
        //       children: [
        //         firstRoute
        //       ]
        //     }
        //   )
        // }
        // accessedRoutes.push({
        // // accessedRoutes.push({
        //   path: '/profile/password',
        //   component: () => import('@/views/profile/password'),
        //   name: 'password',
        //   meta: { title: '修改密码', noCache: true },
        //   hidden: true
        // }) 
        //测试组件开始
        accessedRoutes=accessedRoutes.concat([{
          path: '/componts',
          component: Layout,
          name: 'components',
          redirect: 'dashboard',
          meta: { title: '组件', icon: 'user', affix: true },
          children: [
            // {
            //   path: 'dashboard',
            //   component: () => import('@/views/dashboard/index'),
            //   name: 'Dashboard',
            //   hidden: true,
            //   meta: { title: '首页', icon: 'dashboard', affix: true }
            // },
            {
              path: '/components/CodeGeneratorList',
              component: () => import('@/views/components/code/CodeGeneratorList'),
              name: 'CodeGeneratorList',
              meta: { title: '代码管理',icon:"user", noCache: true },
              hidden: false
            },
              {
              path: '/components/Department',
              component: () => import('@/views/components/department/Department'),
              name: 'Department',
              meta: { title: '部门管理',icon:"user", noCache: true },
              hidden: false
            },
              {
              path: '/components/DictList',
              component: () => import('@/views/components/dict/DictList'),
              name: 'DictList',
              meta: { title: '字典管理',icon:"user", noCache: true },
              hidden: false
            },
              {
              path: '/components/HashTable',
              component: () => import('@/views/components/dict/HashTable'),
              name: 'HashTable',
              meta: { title: '哈希表格',icon:"user", noCache: true },
              hidden: false
            },
              {
              path: '/components/ComFormExp01',
              component: () => import('@/views/components/form/ComFormExp01'),
              name: 'ComFormExp01',
              meta: { title: '通用表单',icon:"user", noCache: true },
              hidden: false
            },
              {
              path: '/components/ComTable',
              component: () => import('@/views/components/form/ComTable'),
              name: 'ComTable',
              meta: { title: '通用ComTable',icon:"user", noCache: true },
              hidden: false
            },
              {
              path: '/components/RoleList',
              component: () => import('@/views/components/role/RoleList'),
              name: 'RoleList',
              meta: { title: '角色列表',icon:"user", noCache: true },
              hidden: false
            },
              {
              path: '/components/Menu',
              component: () => import('@/views/components/menus/Menu'),
              name: 'Menu',
              meta: { title: '菜单列表',icon:"user", noCache: true },
              hidden: false
            },
              {
              path: '/components/MenusConfig',
              component: () => import('@/views/components/menus/MenusConfig'),
              name: 'MenusConfig',
              meta: { title: '菜单配置',icon:"user", noCache: true },
              hidden: false
            },
              {
              path: '/components/UserConfig',
              component: () => import('@/views/components/user/UserConfig'),
              name: 'UserConfig',
              meta: { title: '用户列表',icon:"user", noCache: true },
              hidden: false
            },
          ]
        }])
        // accessedRoutes.children.push(
        //   {
        //   path: '/components/CodeGeneratorList',
        //   component: () => import('@/views/components/code/CodeGeneratorList'),
        //   name: 'CodeGeneratorList',
        //   meta: { title: '代码管理',icon:"user", noCache: true },
        //   hidden: false
        // },
        //   {
        //   path: '/components/Department',
        //   component: () => import('@/views/components/department/Department'),
        //   name: 'Department',
        //   meta: { title: '部门管理',icon:"user", noCache: true },
        //   hidden: false
        // },
        //   {
        //   path: '/components/DictList',
        //   component: () => import('@/views/components/dict/DictList'),
        //   name: 'DictList',
        //   meta: { title: '字典管理',icon:"user", noCache: true },
        //   hidden: false
        // },
        //   {
        //   path: '/components/HashTable',
        //   component: () => import('@/views/components/dict/HashTable'),
        //   name: 'HashTable',
        //   meta: { title: '哈希表格',icon:"user", noCache: true },
        //   hidden: false
        // },
        //   {
        //   path: '/components/ComFormExp01',
        //   component: () => import('@/views/components/form/ComFormExp01'),
        //   name: 'ComFormExp01',
        //   meta: { title: '通用表单',icon:"user", noCache: true },
        //   hidden: false
        // },
        //   {
        //   path: '/components/ComTable',
        //   component: () => import('@/views/components/form/ComTable'),
        //   name: 'ComTable',
        //   meta: { title: '通用ComTable',icon:"user", noCache: true },
        //   hidden: false
        // },
        //   {
        //   path: '/components/RoleList',
        //   component: () => import('@/views/components/role/RoleList'),
        //   name: 'RoleList',
        //   meta: { title: '角色列表',icon:"user", noCache: true },
        //   hidden: false
        // },
        //   {
        //   path: '/components/Menu',
        //   component: () => import('@/views/components/menus/Menu'),
        //   name: 'Menu',
        //   meta: { title: '菜单列表',icon:"user", noCache: true },
        //   hidden: false
        // },
        //   {
        //   path: '/components/MenusConfig',
        //   component: () => import('@/views/components/menus/MenusConfig'),
        //   name: 'MenusConfig',
        //   meta: { title: '菜单配置',icon:"user", noCache: true },
        //   hidden: false
        // },
        //   {
        //   path: '/components/UserConfig',
        //   component: () => import('@/views/components/user/UserConfig'),
        //   name: 'UserConfig',
        //   meta: { title: '用户列表',icon:"user", noCache: true },
        //   hidden: false
        // },
        // )
        //测试组件结束
        accessedRoutes.push({ path: '*', redirect: '/404', hidden: true })
        commit('SET_ROUTES', accessedRoutes)

        // accessedRoutes.push({
        //   path: '/profile/password',
        //   component: () => import('@/views/profile/password'),
        //   name: 'password',
        //   meta: { title: '修改密码', noCache: true },
        //   hidden: true
        // }) 
        // accessedRoutes.push({ path: '*', redirect: '/404', hidden: true })
        // commit('SET_ROUTES', accessedRoutes)
        resolve()
      })
    }
  }
}

export default permission
